package dongshi.daddy.encryptionAndDecryption.rsa;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RsaTest {
    private static String PRIVATE_KEY;
    private static String PUBLIC_KEY;

    private static byte[] PRIVATE_KEY_BYTE;
    private static byte[] PUBLIC_KEY_BYTE;
//    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥

    public static void main(String[] args) {
        try {
            // 生成公钥和私钥
            genKeyPair();
            System.out.println("私钥：" + PRIVATE_KEY);
            System.out.println("公钥：" + PUBLIC_KEY);
            String message = "df723820";

//            enPublicAndDecPrivate(message);

            enPrivateAndDecPublic(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void enPrivateAndDecPublic(String message) throws Exception {
        System.out.println("***私钥加密公钥解密开始***");
        byte[] messageEnByte = encryptByPrivateKey(message.getBytes(), PRIVATE_KEY_BYTE);
        System.out.println(message + "\t加密后的字符串为:" + Base64.encodeBase64String(messageEnByte));
//            System.out.println(messageEn.substring(0, 2));
        // 修改内容将无法解密javax.crypto.BadPaddingException: Decryption error
//            messageEn = "Ky" + messageEn.substring(0, 2);
        String messageDe = decryptByPublicKey(messageEnByte, PUBLIC_KEY_BYTE);
        System.out.println("还原后的字符串为:" + messageDe);
        System.out.println("***私钥加密公钥解密结束***");
    }

    // 公钥加密，私钥解密
    private static String enPublicAndDecPrivate(String message) throws Exception {
        System.out.println("***公钥加密私钥解密开始***");
        String messageEn = encryptWithPublic(message, PUBLIC_KEY);
        System.out.println(message + "\t加密后的字符串为:" + messageEn);
        System.out.println(messageEn.substring(0, 2));
        // 修改内容将无法解密javax.crypto.BadPaddingException: Decryption error
//            messageEn = "Ky" + messageEn.substring(0, 2);
        String messageDe = decryptWithPublic(messageEn, PRIVATE_KEY);
        System.out.println("还原后的字符串为:" + messageDe);
        System.out.println("***公钥加密私钥解密结束***");
        return messageEn;
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encryptWithPublic(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decryptWithPublic(String str, String privateKey) throws Exception {
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    /**
     * 随机生成密钥对
     *
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        PUBLIC_KEY_BYTE = publicKey.getEncoded();
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        PRIVATE_KEY_BYTE = privateKey.getEncoded();
        // 将公钥和私钥保存到Map
        /*keyMap.put(0,publicKeyString);  //0表示公钥
        keyMap.put(1,privateKeyString);  //1表示私钥*/
        PRIVATE_KEY = privateKeyString;
        PUBLIC_KEY = publicKeyString;
    }

    public static String RSA_ALGORITHM = "RSA";

    /**
     * 私钥加密
     *
     * @param data 待加密数据
     * @param key  密钥
     * @return byte[] 加密数据
     */
    public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {
//    public static String encryptByPrivateKey(byte[] data, byte[] key) throws Exception {
        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        //生成私钥
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
//        return new String(cipher.doFinal(data));
//        return Base64.encode(cipher.doFinal(data));
    }

    /**
     * 公钥解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     */
//    public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {
    public static String decryptByPublicKey(byte[] data, byte[] key) throws Exception {
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        //产生公钥
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
        //数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        return new String(cipher.doFinal(data));
    }
}
